import { Repository } from 'typeorm';
import { AppDataSource } from '../config/database';
import { Post } from '../entities/Post';
import { User } from '../entities/User';
import { validate } from 'class-validator';

export class PostService {
  private getPostRepository(): Repository<Post> {
    if (!AppDataSource.isInitialized) {
      throw new Error('数据库连接未初始化。请确保数据库已正确配置并连接。');
    }
    return AppDataSource.getRepository(Post);
  }

  private getUserRepository(): Repository<User> {
    if (!AppDataSource.isInitialized) {
      throw new Error('数据库连接未初始化。请确保数据库已正确配置并连接。');
    }
    return AppDataSource.getRepository(User);
  }

  async createPost(postData: Partial<Post>, authorId: number): Promise<Post> {
    const userRepository = this.getUserRepository();
    const postRepository = this.getPostRepository();
    
    // 验证作者是否存在
    const author = await userRepository.findOne({ where: { id: authorId } });
    if (!author) {
      throw new Error('作者不存在');
    }

    const post = postRepository.create({
      ...postData,
      authorId,
    });
    
    // 验证数据
    const errors = await validate(post);
    if (errors.length > 0) {
      throw new Error(`验证失败: ${errors.map(e => Object.values(e.constraints || {})).flat().join(', ')}`);
    }

    return await postRepository.save(post);
  }

  async findPostById(id: number): Promise<Post | null> {
    const postRepository = this.getPostRepository();
    return await postRepository.findOne({
      where: { id },
      relations: ['author'],
    });
  }

  async getAllPosts(page: number = 1, limit: number = 10, publishedOnly: boolean = false): Promise<{ posts: Post[]; total: number }> {
    const postRepository = this.getPostRepository();
    const whereCondition = publishedOnly ? { published: true } : {};
    
    const [posts, total] = await postRepository.findAndCount({
      where: whereCondition,
      relations: ['author'],
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    });

    return { posts, total };
  }

  async getPostsByAuthor(authorId: number, page: number = 1, limit: number = 10): Promise<{ posts: Post[]; total: number }> {
    const postRepository = this.getPostRepository();
    const [posts, total] = await postRepository.findAndCount({
      where: { authorId },
      relations: ['author'],
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    });

    return { posts, total };
  }

  async updatePost(id: number, updateData: Partial<Post>, authorId?: number): Promise<Post | null> {
    const postRepository = this.getPostRepository();
    const post = await this.findPostById(id);
    if (!post) {
      return null;
    }

    // 如果指定了作者ID，验证权限
    if (authorId && post.authorId !== authorId) {
      throw new Error('无权限修改此文章');
    }

    Object.assign(post, updateData);
    
    // 如果发布文章，设置发布时间
    if (updateData.published && !post.publishedAt) {
      post.publishedAt = new Date();
    }
    
    // 验证数据
    const errors = await validate(post);
    if (errors.length > 0) {
      throw new Error(`验证失败: ${errors.map(e => Object.values(e.constraints || {})).flat().join(', ')}`);
    }

    return await postRepository.save(post);
  }

  async deletePost(id: number, authorId?: number): Promise<boolean> {
    const postRepository = this.getPostRepository();
    const post = await this.findPostById(id);
    if (!post) {
      return false;
    }

    // 如果指定了作者ID，验证权限
    if (authorId && post.authorId !== authorId) {
      throw new Error('无权限删除此文章');
    }

    const result = await postRepository.delete(id);
    return result.affected !== 0;
  }

  async publishPost(id: number, authorId?: number): Promise<Post | null> {
    return await this.updatePost(id, { 
      published: true, 
      publishedAt: new Date() 
    }, authorId);
  }

  async unpublishPost(id: number, authorId?: number): Promise<Post | null> {
    return await this.updatePost(id, { 
      published: false, 
      publishedAt: undefined 
    }, authorId);
  }
}